<?php

namespace app\admin\controller\rush;

use app\api\model\RushOrderEntrust;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 抢购订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\rush\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\rush\Order;
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("complainStatusList", $this->model->getComplainStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map = [];
            $buyer_id = $this->request->get('buyer_id');
            $seller_id = $this->request->get('seller_id');
            if($buyer_id){
                $map['buyer_id'] = $buyer_id;
            }
            if($seller_id){
                $map['seller_id'] = $seller_id;
            }
            $list = $this->model
                    ->with(['buyer','seller'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','order_no','order_status','payment_voucher','complain_status','express_company','express_no','createtime','rushtime','confirmtime','goods_name','goods_price','goods_image','time_name']);
                $row->visible(['buyer']);
				$row->getRelation('buyer')->visible(['bank_name','bank_card_no','bank_card_holder','nickname','mobile']);
				$row->visible(['seller']);
				$row->getRelation('seller')->visible(['bank_name','bank_card_no','bank_card_holder','nickname','mobile']);
            }

            //总付款流水
            $pay_total = $this->model
                ->with(['buyer','seller'])
                ->where($where)
                ->where($map)
                ->where('confirmtime','>',0)
                ->sum('goods_price');
            //今日付款流水
            $pay_today = $this->model
                ->with(['buyer','seller'])
                ->where($where)
                ->where($map)
                ->whereTime('confirmtime','today')
                ->sum('goods_price');

            $result = array("total" => $list->total(), "rows" => $list->items(), "pay_total" => $pay_total, "pay_today" => $pay_today);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 待付款-取消订单
     */
    public function buyerCancel($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            $row['order_status'] != '0' && $this->error('订单不合法');
            Db::startTrans();
            try {
                $res = \app\api\controller\RushBuyer::cancelAction($row);
                $res['code'] == 0 && $this->error($res['msg']);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * 待付款-确认支付
     */
    public function buyerPay($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            $row['order_status'] != '0' && $this->error('订单不合法');
            Db::startTrans();
            try {
                $res = \app\api\controller\RushBuyer::confirmPayAction($row);
                $res['code'] == 0 && $this->error($res['msg']);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * 待确认-买家未支付
     */
    public function buyerNoPay($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            $row['order_status'] != '1' && $this->error('订单不合法');
            Db::startTrans();
            try {
                $row->allowField(true)->save(['order_status'=>'0']);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * 待确认-确认收款
     */
    public function sellerGetMoney($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            $row['order_status'] != '1' && $this->error('订单不合法');
            Db::startTrans();
            try {
                $res = \app\api\controller\RushSeller::confirmGetMoneyAction($row);
                $res['code'] == 0 && $this->error($res['msg']);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * 待上架-确认未收款
     */
    public function sellerNoGetMoney($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            $row['order_status'] != '2' && $this->error('订单不合法');
            Db::startTrans();
            try {
                $row->allowField(true)->save(['order_status'=>'1']);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * 待上架-上架
     */
    public function buyerUp($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            $row['order_status'] != '2' && $this->error('订单不合法');
            Db::startTrans();
            try {
                //计算委托上架金额和委托费用
                $entrust_rate = config('site.entrust_rate');
                $entrust_price = round($row['goods_price'] * (1+$entrust_rate/100),2);
                $service_rate = config('site.service_rate');
                $service_fee = round($row['goods_price'] * ($service_rate/100),2);
                //创建委托订单
                $entrust = RushOrderEntrust::create([
                    'entrust_no' => get_order_sn('E'),
                    'entrust_price' => $entrust_price,
                    'service_fee' => $service_fee,
                    'coupon_price' => 0,
                    'pay_price' => $service_fee,
                    'user_coupon_id' => 0,
                    //记录抢购订单数据
                    'order_id' => $row['id'],
                    'order_no' => $row['order_no'],
                    'goods_price' => $row['goods_price'],
                ]);
                $res = \app\api\controller\RushBuyer::entrustNotifyAction($entrust,$row,'');
                $res['code'] == 0 && $this->error($res['msg']);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * 待上架-提货
     */
    public function buyerTakeover($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            $row['order_status'] != '2' && $this->error('订单不合法');
            Db::startTrans();
            try {
                $row->allowField(true)->save(['order_status' => '4']);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * 已提货-取消提货
     */
    public function buyerTakeoverCancel($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            $row['order_status'] != '4' && $this->error('订单不合法');
            Db::startTrans();
            try {
                $res = \app\api\controller\RushBuyer::takeoverCancelAction($row);
                $res['code'] == 0 && $this->error($res['msg']);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * 填写物流信息
     */
    public function express($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
